/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.core;

import org.latestbit.smartobjects.IAsyncServerCallback;
import org.latestbit.smartobjects.RequestContext;
import org.latestbit.smartobjects.coders.CallInterfaceOperationRequest;
import org.latestbit.smartobjects.coders.CallInterfaceOperationResponse;
import org.latestbit.smartobjects.exceptions.SmartBusSystemException;
import org.latestbit.smartobjects.io.ResizableByteBuffer;
import org.latestbit.smartobjects.network.*;

public class ServerCallback implements IAsyncServerCallback {
	private String operationName;
	private INetworkCommand request;	
	private ICommandProcessor commandProcessor;
	private RequestContext requestContext;
	
	public void setOperationName ( String operationName ) {
		this.operationName = operationName;
	}
	
	@Override
	public String getOperationName() {
		return this.operationName;
	}
	
	public void setRequest ( INetworkCommand request ) {
		this.request = request;
	}
	
	@Override
	public INetworkCommand getRequest ( ) {
		return this.request;
	}

	public void setCommandProcessor(ICommandProcessor commandProcessor) {
		this.commandProcessor = commandProcessor;
	}

	public ICommandProcessor getCommandProcessor() {
		return commandProcessor;
	}
	
	
	public void setRequestContext(RequestContext requestContext) {
		this.requestContext = requestContext;
	}

	@Override
	public RequestContext getRequestContext() {
		return requestContext;
	}

	@Override
	public void sendSystemException ( SmartBusSystemException uex ) {
		CallInterfaceOperationRequest callRequest = ( CallInterfaceOperationRequest ) getRequest();
		callRequest.getBuffer().getBuffer().clear();
		ResizableByteBuffer writeBuffer = callRequest.getBuffer();
		
		CallInterfaceOperationResponse callResponse = callRequest.createResponse(writeBuffer);
		callResponse.setExceptionFlag(true);
		callResponse.setExceptionMessage ( uex.getMessage() );
		callResponse.setExceptionInterfaceId ( "SmartBusSystemException" );

		try {
			callResponse.beginSerialize();
			callResponse.finishSerialize();

		
			getCommandProcessor().sendResponse(getRequestContext().getConnectionHandler(), callResponse);
		}
		catch( Exception ex) {
			// FIXME: remove print stack trace
			ex.printStackTrace();
		}	
	}



}
